<template>
  <div class="hello">
    <fks-query-page
      ref="query"
      :data="tableData"
      :border="true"
      @query="getData"
      @clear="clear"
      :total="total"
      :pageSize.sync="pageSize"
      :currentPage.sync="pageNo"
      :hideSwitch.sync="hideSwitch"
      :page-sizes="[10, 20, 50, 100]"
      style="min-height: 500px; height: 100%"
      tableName="UE实例管理"
      layout="total, sizes, prev, pager, next, jumper"
      :highlight-current-row="true"
      @row-click="rowClick"
      @select="handleSelection"
    >
      <template slot="search">
        <fks-search-item label="实例名称" for="input">
          <fks-input placeholder="请输入实例名称" v-model="search"></fks-input>
        </fks-search-item>
      </template>
      <template slot="button">
        <fks-button
          type="primary"
          plain
          icon="fks-icon-plus"
          @click="addInstance"
        >
          新增实例
        </fks-button>
        <fks-button
          plain
          type="success"
          icon="fks-icon-next"
          @click="startInstance"
        >
          启动实例
        </fks-button>
        <fks-button
          plain
          type="info"
          icon="fks-icon-prohibit"
          @click="stopInstance"
        >
          停止实例
        </fks-button>
        <fks-button
          plain
          type="danger"
          icon="fks-icon-delete"
          @click="deleteInstance"
        >
          删除实例
        </fks-button>
      </template>
      <template>
        <fks-table-column type="selection" width="55" />
        <fks-table-column
          prop="name"
          label="实例名称"
          width="240"
        ></fks-table-column>
        <fks-table-column prop="port" label="实例端口" width="80">
        </fks-table-column>
        <fks-table-column
          prop="projectName"
          label="UE工程名称"
          width="240"
        ></fks-table-column>
        <fks-table-column prop="totalRuntimes" label="实例运行时长" width="240">
          <template #default="scope">
            <span v-show="scope.row.runStatus">
              {{ instanceTotalRunTime(scope.row.totalRuntimes) }}
            </span>
          </template>
        </fks-table-column>
        <fks-table-column prop="runStatus" label="运行状态" width="240">
          <template slot-scope="scope">
            <div class="statusBtn_negative" v-show="!scope.row.runStatus">
              未启动
            </div>
            <div class="statusBtn_positive" v-show="scope.row.runStatus">
              运行中
            </div>
          </template>
        </fks-table-column>
        <fks-table-column prop="connectStatus" label="连接状态" width="240">
          <template slot-scope="scope">
            <div class="statusBtn_negative" v-show="!scope.row.connectStatus">
              未连接
            </div>
            <div class="statusBtn_positive" v-show="scope.row.connectStatus">
              已连接
            </div>
          </template>
        </fks-table-column>
        <fks-table-column prop="uploadDate" label="创建时间"></fks-table-column>
        <fks-table-column fixed="right" label="操作" width="160">
          <template slot-scope="scope">
            <fks-button @click="testStream(scope.row)" text size="medium">
              测试
            </fks-button>
            <fks-button text size="medium" @click="copyStream(scope.row)">
              复制
            </fks-button>
            <fks-button dangerText size="medium" @click="kickOff(scope.row)">
              踢人
            </fks-button>
          </template>
        </fks-table-column>
      </template>
    </fks-query-page>
    <add-dialog
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      @refresh="getData()"
    ></add-dialog>
  </div>
</template>

<script>
import {
  getUeInstance,
  startUeInstance,
  stopUeInstance,
  deleteUeInstance,
  closeClient,
} from "../apis/ueinstance";
import { connectUeMsg, disconnectUeMsg } from "../utils/ws";
import { formatSeconds, copyText } from "../utils/index";
import addDialog from "./addDialog.vue";
import { useDeleteConfirmation } from "../hooks/useDeleteConfirm";
export default {
  setup() {
    const { deleteData, isDeleting } = useDeleteConfirmation();
    return {
      deleteData,
      isDeleting,
    };
  },
  components: { addDialog },
  data() {
    return {
      search: "",
      preciseSearch: false,
      hideSwitch: true,
      tableData: [],
      pageSize: 15,
      pageNo: 1,
      total: 0,
      selectList: [],
      selectIds: [],
      dialogVisible: false,
    };
  },
  computed: {
    instanceTotalRunTime() {
      return (val) => {
        return formatSeconds(Math.ceil(val) / 1000);
      };
    },
  },
  methods: {
    clear() {
      this.search = "";
      this.getData();
    },
    getData() {
      const data = {
        pageNo: this.pageNo,
        pageSize: this.pageSize,
        search: this.search,
      };
      getUeInstance(data).then((res) => {
        if (res.status) {
          this.tableData = res.data;
          this.total = res.page.total;
        }
      });
    },
    // 创建实例，打开弹窗
    addInstance() {
      this.dialogVisible = true;
    },
    /**
     * @description: 启动实例
     * @return {*}
     */
    startInstance() {
      if (!this.selectIds.length) {
        this.$notify({
          title: "Info",
          message: "请先选择实例，在进行操作！",
          type: "info",
        });
        return;
      }
      startUeInstance({
        ids: this.selectIds,
      }).then((res) => {
        if (res?.status) {
          this.selectIds.length = 0;
          this.$message({
            type: "success",
            message: "启动成功!",
          });
          // 更新数据
          this.getData();
        }
      });
    },
    stopInstance() {
      if (!this.selectIds.length) {
        this.$notify({
          title: "Info",
          message: "请先选择实例，在进行操作！",
          type: "info",
        });
        return;
      }
      stopUeInstance({
        ids: this.selectIds,
      }).then((res) => {
        if (res?.status) {
          this.selectIds.length = 0;
          this.$message({
            type: "success",
            message: "停止成功!",
          });
          // 更新数据
          this.getData();
        }
      });
    },
    deleteInstance() {
      this.deleteData(this.selectIds, (data) => {
        return deleteUeInstance({
          ids: data,
        }).then((res) => {
          if (res?.status) {
            this.selectIds.length = 0;
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            // 更新数据
            this.getData();
          }
        });
      });
    },
    rowClick(val) {
      console.log("rowClick", val);
    },
    handleSelection(val) {
      this.selectList = [...val];
      this.selectIds = this.selectList.map((item) => {
        return item.id;
      });
      // console.log("this.selectList", this.selectList, this.selectIds);
    },
    testStream(data) {
      if (data.runStatus) {
        window.open(`/#/pixelstream/${data.id}`);
      } else {
        this.$notify({
          title: "警告",
          message: "请先运行实例！",
          type: "warning",
        });
      }
    },
    copyStream(data) {
      let url = "";
      if (data.useHttps) {
        url = `wss://${data.instanceIp}:${data.port}`;
      } else {
        url = `ws://${data.instanceIp}:${data.port}`;
      }
      copyText(url);
    },
    kickOff(data) {
      if (!data.connectStatus) {
        this.$notify({
          title: "警告",
          message: "当前实例无用户连接！",
          type: "warning",
        });
        return;
      }
      closeClient({
        instanceId: data.id,
        connectionId: data.connections[0].id,
      }).then((res) => {
        if (res.status) {
          this.$message({
            type: "success",
            message: "关闭连接成功!",
          });
        }
      });
    },
    wsOpen(res) {
      console.log("wsopen=", res);
    },
    wsMessage(res) {
      // console.log("wsMessage=", res);
      const message = JSON.parse(res.data);
      console.log("message=", message);
      if (message.data.target == "ueinstance") {
        this.getData();
      }
    },
    wsError(res) {
      console.log("wsError=", res);
    },
  },
  created() {
    this.getData();
    connectUeMsg(this.wsOpen, this.wsMessage, this.wsError);
  },
  mounted() {},
  beforeDestroy() {
    disconnectUeMsg();
  },
};
</script>
<style scoped>
.statusBtn_negative,
.statusBtn_positive {
  color: #909399;
  background: #f4f4f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 8px 12px;
  font-size: 14px;
  width: 70px;
  height: 36px;
  line-height: 20px;
  margin: 0 auto;
}
.statusBtn_positive {
  color: #40bb5a;
  background: #ecf8ef;
  border-color: #b3e4bd;
}
</style>
